package com.heima.user.controller;

import com.heima.common.dto.ResponseResult;
import com.heima.user.dto.UserDomain;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.stream.Collectors;

/**
 * @author: itheima
 * @create: 2022-01-05 12:19
 */
@RestController
public class TestController {

    /**
     * 参数校验框架
     *
     * @param userDomain
     * @param bindingResult 封装校验结果对象
     * @return
     */
    @PostMapping("/test/user")
    public ResponseResult<UserDomain> saveUser(@Valid @RequestBody UserDomain userDomain, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            //参数校验失败
            String errorMsg = bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(","));
            return ResponseResult.errorResult(400, errorMsg);
        }
        return ResponseResult.okResult("请求成功！");
    }

}
